package cn.wolfcode.web.controller;


import cn.wolfcode.domain.Employee;
import cn.wolfcode.exception.MyException;
import cn.wolfcode.quest.JsonResult;
import cn.wolfcode.service.IEmployeeService;
import cn.wolfcode.service.ILoginService;
import cn.wolfcode.service.IPermissionService;
import cn.wolfcode.util.UserContext;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class LoginController {
    @Autowired
    private ILoginService loginService;
    @Autowired
    private IPermissionService permissionService;
    @Autowired
    private IEmployeeService employeeService;
    @RequestMapping("/login")
    @ResponseBody
    public JsonResult login(String username, String password, HttpSession session) {
        Employee employee = employeeService.QueryByName(username);

            System.out.println("进入方法");
            JsonResult jsonResult = new JsonResult();
            try {
                Subject subject = SecurityUtils.getSubject();
                UsernamePasswordToken token = new UsernamePasswordToken(username, password);
                subject.login(token);
                return jsonResult;
            }/*catch (MyException e){
            jsonResult.setSuccess(false);
            jsonResult.setMsg(e.getMessage());
            return jsonResult;
        } */ catch (UnknownAccountException e) {
               e.printStackTrace();
                jsonResult.setSuccess(false);
                jsonResult.setMsg("账号不存在");
                return jsonResult;
            } catch (IncorrectCredentialsException e) {
                jsonResult.setSuccess(false);
                jsonResult.setMsg("密码错误");
                return jsonResult;
            }/*catch (MyException e){
                e.printStackTrace();
                jsonResult.setSuccess(false);
                jsonResult.setMsg(e.getMessage());
                return jsonResult;
            }*/



            catch (Exception e) {
               e.printStackTrace();
                jsonResult.setSuccess(false);
                if(e instanceof AuthenticationException){
                    jsonResult.setMsg(e.getMessage());
                }else {
                    jsonResult.setMsg("其他的异常");
                }
                return jsonResult;
            }

    }

 /*   //登出
    @RequestMapping("/logout")
    public String logout(HttpSession session){
        //销毁会话域
        session.invalidate();
        //重定向到登录界面
        return "redirect:/login.html";
    }*/
}
